package com.atdel.demo15;


import com.atdel.demo06.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo15
 * @Author: Del
 * @CreateTime: 2025-03-17  09:52
 * @Description: TODO
 * @Version: 1.0
 */
public class BeanUtil<T> {
    public T getBean(String className) {
        try {
            // 加载类
            Class<?> clazz = Class.forName(className);
            // 通过加载器实例化对象
            return (T) clazz.getDeclaredConstructor().newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException |
                 InvocationTargetException e) {
            throw new RuntimeException("Failed to create bean for class: " + className, e);
        }

    }

    public T getBean(T bean) {
        // 检查输入是否为 null
        if (bean == null) {
            return null;
        }
        Class<?> clazz = bean.getClass();
        try {
            // 获取类名并尝试加载类（假设这是方法的核心功能）
            // 获取默认构造函数
            Constructor<?> constructor = clazz.getDeclaredConstructor();

            // 获取指定参数的构造函数
            Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(String.class, int.class);

            // 突破私有构造函数限制
            if (!constructor.isAccessible()) {
                constructor.setAccessible(true);
            }

            // 类型安全转换（警告需要压制）
            return (T) constructor.newInstance();

            // 创建一个实例并返回
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        BeanUtil<Student> beanUtil = new BeanUtil<>();
        Student student;
        try {
            student = beanUtil.getBean("com.atdel.demo15.Student");
        } catch (RuntimeException e) {
            System.err.println("Failed to create Student bean: " + e.getMessage());
            return;
        }

        student.setName("张三");
        student.setAge(18);
        System.out.println(student.getClass().getName());

        Method method = student.getClass().getDeclaredMethod("nation", String.class);
        method.setAccessible(true);
        method.invoke(student, "中国");

        student.setName("张三");
        student.setAge(18);
        student.study();


    }
}
